<?php
namespace App\Support;

class Excel {

	public function readExcel(string $filePath, array $fields) {
		$array = explode('.', $filePath);
		$objReader = \PHPExcel_IOFactory::createReader(end($array) == "xlsx" ? "Excel2007" : "Excel5");
		$objReader->setReadDataOnly(true);
		$objPHPExcel = $objReader->load($filePath, $encode = 'utf-8');
		$objWorksheet = $objPHPExcel->getActiveSheet();
		$highestRow = $objWorksheet->getHighestRow();
		$highestColumn = $objWorksheet->getHighestColumn();
		$highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
		for ($row = 2; $row <= $highestRow; $row++) {
			$data = [];
			foreach ($fields as $key => $value) {
				$data[$key] = $objWorksheet->getCell($value . $row)->getValue();
			}

			yield $data;
		}
	}

	public function exportExcel(array $data, array $fields, string $title) {
		$objExcel = new \PHPExcel();
		$objProps = $objExcel->getProperties();
		$objExcel->setActiveSheetIndex(0);
		$objActSheet = $objExcel->getActiveSheet();
		$objActSheet->setTitle($title);
		$i = 1;
		foreach ($fields as $key => $value) {
			$objActSheet->setCellValue($key . $i, $value['title']);
		}
		$list = $this->yeildData($data);
		foreach ($list as $value) {
			$i++;
			foreach ($fields as $k => $v) {
				$objActSheet->setCellValue($k . $i, $value[$v['key']]);
			}
		}
		$objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
		ob_end_clean();
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="' . iconv("utf-8", 'gbk', $title) . '"');
		header('Cache-Control: max-age=0');
		$objWriter->save('php://output');
	}

	private function yeildData(array $data) {
		foreach ($data as $key => $value) {
			yield $value;
		}
	}
}